#!/usr/bin/env python3
"""
系统管理路由
"""

from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio.session import AsyncSession
from sqlalchemy.future import select

from app.database.session import get_db
from app.models.system_config import SystemConfig
from app.schemas.system_config import (
    SystemConfigBase,
    SystemConfigCreate,
    SystemConfigUpdate,
    SystemConfigResponse,
    SystemConfigListResponse,
)
from app.services.audit_service import audit_log

router = APIRouter()


@router.get("/configs", response_model=SystemConfigListResponse)
async def get_system_configs(skip: int = 0, limit: int = 100, db: AsyncSession = Depends(get_db)):
    """
    获取系统配置列表

    Args:
        skip: 跳过记录数
        limit: 限制记录数
        db: 数据库会话

    Returns:
        SystemConfigListResponse: 系统配置列表响应
    """
    try:
        # 查询系统配置
        result = await db.execute(
            select(SystemConfig).order_by(SystemConfig.created_at.desc()).offset(skip).limit(limit)
        )
        configs = result.scalars().all()

        # 查询总数
        count_result = await db.execute(select(SystemConfig))
        total = len(count_result.scalars().all())

        return SystemConfigListResponse(configs=list(configs), total=total, skip=skip, limit=limit)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取系统配置失败: {str(e)}")


@router.get("/configs/{config_key}", response_model=SystemConfigResponse)
async def get_system_config(config_key: str, db: AsyncSession = Depends(get_db)):
    """
    获取单个系统配置

    Args:
        config_key: 配置键名
        db: 数据库会话

    Returns:
        SystemConfigResponse: 系统配置响应
    """
    try:
        result = await db.execute(select(SystemConfig).where(SystemConfig.config_key == config_key))
        config = result.scalar_one_or_none()

        if not config:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"配置 '{config_key}' 不存在")

        return SystemConfigResponse(
            config=SystemConfigBase(
                key=config.config_key,
                value=config.config_value,
                description=config.description,
                is_encrypted=config.is_encrypted,
            ),
            created_at=config.created_at,
            updated_at=config.updated_at,
        )

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取系统配置失败: {str(e)}")


@router.post("/configs", response_model=SystemConfigResponse)
async def create_system_config(config_data: SystemConfigCreate, db: AsyncSession = Depends(get_db)):
    """
    创建系统配置

    Args:
        config_data: 配置创建数据
        db: 数据库会话

    Returns:
        SystemConfigResponse: 系统配置响应
    """
    try:
        # 检查配置是否已存在
        result = await db.execute(select(SystemConfig).where(SystemConfig.config_key == config_data.key))
        existing_config = result.scalar_one_or_none()

        if existing_config:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"配置 '{config_data.key}' 已存在")

        # 创建新配置
        new_config = SystemConfig()
        new_config.config_key = config_data.key
        new_config.config_value = config_data.value
        new_config.description = config_data.description
        new_config.is_encrypted = config_data.is_encrypted
        new_config.created_at = datetime.now()
        new_config.updated_at = datetime.now()

        db.add(new_config)  # type: ignore[attr-defined]
        await db.commit()
        await db.refresh(new_config)

        # 记录审计日志
        await audit_log(
            db=db,
            operator="system",
            operation_type="create_config",
            operation_target="system_config",
            operation_details={"config_key": new_config.config_key, "config_value": new_config.config_value},
        )

        return SystemConfigResponse(
            config=SystemConfigBase(
                key=new_config.config_key,
                value=new_config.config_value,
                description=new_config.description,
                is_encrypted=new_config.is_encrypted,
            ),
            created_at=new_config.created_at,
            updated_at=new_config.updated_at,
        )

    except HTTPException:
        raise
    except Exception as e:
        await db.rollback()
        raise HTTPException(status_code=500, detail=f"创建系统配置失败: {str(e)}")


@router.put("/configs/{config_key}", response_model=SystemConfigResponse)
async def update_system_config(config_key: str, config_data: SystemConfigUpdate, db: AsyncSession = Depends(get_db)):
    """
    更新系统配置

    Args:
        config_key: 配置键名
        config_data: 配置更新数据
        db: 数据库会话

    Returns:
        SystemConfigResponse: 系统配置响应
    """
    try:
        result = await db.execute(select(SystemConfig).where(SystemConfig.config_key == config_key))
        config = result.scalar_one_or_none()

        if not config:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"配置 '{config_key}' 不存在")

        # 更新配置
        old_value = config.config_value

        if config_data.value is not None:
            config.config_value = config_data.value
        if config_data.description is not None:
            config.description = config_data.description
        if config_data.is_encrypted is not None:
            config.is_encrypted = config_data.is_encrypted

        await db.commit()
        await db.refresh(config)

        # 记录审计日志
        await audit_log(
            db=db,
            operator="system",
            operation_type="update_config",
            operation_target="system_config",
            operation_details={"config_key": config.config_key, "old_value": old_value, "new_value": config.config_value},
        )

        return SystemConfigResponse(
            config=SystemConfigBase(
                key=config.config_key,
                value=config.config_value,
                description=config.description,
                is_encrypted=config.is_encrypted,
            ),
            created_at=config.created_at,
            updated_at=config.updated_at,
        )

    except HTTPException:
        raise
    except Exception as e:
        await db.rollback()
        raise HTTPException(status_code=500, detail=f"更新系统配置失败: {str(e)}")


@router.delete("/configs/{config_key}")
async def delete_system_config(config_key: str, db: AsyncSession = Depends(get_db)):
    """
    删除系统配置

    Args:
        config_key: 配置键名
        db: 数据库会话

    Returns:
        dict: 删除结果
    """
    try:
        result = await db.execute(select(SystemConfig).where(SystemConfig.config_key == config_key))
        config = result.scalar_one_or_none()

        if not config:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"配置 '{config_key}' 不存在")

        # 记录删除前的配置信息
        config_info = {"key": config.config_key, "value": config.config_value, "description": config.description}

        await db.delete(config)
        await db.commit()

        # 记录审计日志
        await audit_log(
            db=db,
            operator="system",
            operation_type="delete_config",
            operation_target="system_config",
            operation_details=config_info,
        )

        return {"message": f"配置 '{config_key}' 删除成功"}

    except HTTPException:
        raise
    except Exception as e:
        await db.rollback()
        raise HTTPException(status_code=500, detail=f"删除系统配置失败: {str(e)}")
